<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '班组名称为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="班组名称" tooltip="考勤班组的显示名称，用于区分不同的班组" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" placeholder="请输入班组名称"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item ref="Entity_Order_FormItem" prop="Entity.Order">
								<template #label>
									<WtmLabelTooltip label="排序" tooltip="班组规则的排序，数值越小越靠前" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.Order" class="width100" :min="0" placeholder="请输入排序"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_Description_FormItem" prop="Entity.Description">
								<template #label>
									<WtmLabelTooltip label="班组描述" tooltip="班组的详细描述信息，说明班组的用途和特点" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Description" type="textarea" :rows="3" clearable placeholder="请输入班组描述"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>排班设置</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_Type_FormItem"
								prop="Entity.Type"
								:rules="[{ required: true, message: '排班类型为必填项', trigger: 'change' }]"
							>
								<template #label>
									<WtmLabelTooltip label="排班类型" tooltip="班组的排班模式（行政班/三班倒/两班倒）" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Type" clearable class="width100" @change="onTypeChange">
									<el-option v-for="item in SHIFT_TYPES" :key="item.key" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 排班模式配置 -->
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.Type">
							<el-form-item
								:prop="stateData.vmModel.Entity.Type === '行政班' ? 'WorkDays' : 'WorkDate'"
								:rules="[
									{ required: true, message: stateData.vmModel.Entity.Type === '行政班' ? '请选择工作日' : '请选择工作日期', trigger: 'change' },
								]"
							>
								<template #label>
									<WtmLabelTooltip label="排班模式" tooltip="排班模式配置：行政班存储工作日，班倒模式存储班次模板" />
								</template>

								<!-- 行政班：多选工作日 -->
								<el-checkbox-group
									v-if="stateData.vmModel.Entity.Type === '行政班'"
									v-model="stateData.vmModel.WorkDays"
									multiple
									clearable
									collapse-tags
									collapse-tags-tooltip
									placeholder="请选择工作日"
									border
								>
									<el-checkbox v-for="item in stateData.shiftItems" :key="item.Value" :label="item.Text" :value="item.Value"></el-checkbox>
								</el-checkbox-group>

								<!-- 班倒模式：选择工作日期和班次标签 -->
								<template v-else>
									<div class="space-y-3">
										<el-date-picker
											v-model="stateData.vmModel.WorkDate"
											type="date"
											placeholder="请选择工作日期"
											format="YYYY-MM-DD"
											value-format="YYYY-MM-DD"
											class="width100 mb-3"
											@change="onWorkDateChange"
										></el-date-picker>
									</div>
									<el-form-item prop="ShiftTag" :rules="[{ required: true, message: '请选择班次标签', trigger: 'change' }]">
										<template #label>
											<WtmLabelTooltip label="班次标签" tooltip="班倒模式的班次标签" />
										</template>
										<el-radio-group v-model="stateData.vmModel.ShiftTag" @change="onShiftTagChange">
											<el-radio v-for="item in stateData.shiftItems" :key="item.Value" :label="item.Value" :value="item.Value">
												{{ item.Text }}
											</el-radio>
										</el-radio-group>
									</el-form-item>
								</template>
							</el-form-item>
						</el-col>

						<!-- 未选择类型时显示提示 -->
						<el-col :xs="24" :lg="24" class="mb20" v-else>
							<el-form-item>
								<template #label>
									<WtmLabelTooltip label="排班模式" tooltip="排班模式配置：行政班存储工作日，班倒模式存储班次模板" />
								</template>
								<el-alert title="请先选择排班类型" type="info" :closable="false" show-icon></el-alert>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.Type && stateData.vmModel.Entity.Type !== '行政班'">
							<SchedulePreview
								:shift-type="stateData.vmModel.Entity.Type"
								:work-date="stateData.vmModel.WorkDate"
								:shift-tag="stateData.vmModel.ShiftTag"
								:shift-sequence="stateData.allShiftItems?.[stateData.vmModel.Entity.Type] || []"
								:auto-calculate="true"
								title="排班预览"
								:show-type-selector="false"
								:show-date-selector="false"
							/>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>班次管理</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="SelectedShiftsIds_FormItem" prop="SelectedShiftsIds">
								<template #label>
									<WtmLabelTooltip label="班次列表" tooltip="该班组下包含的所有考勤班次" />
								</template>
								<el-select
									v-model="stateData.vmModel.SelectedShiftsIds"
									multiple
									filterable
									clearable
									collapse-tags
									collapse-tags-tooltip
									:max-collapse-tags="4"
									placeholder="请选择班次"
									class="width100"
									@change="onShiftsSelectionChange"
								>
									<el-option v-for="item in stateData.AllSysAttendanceShifts" :key="item.Value" :label="item.Text" :value="item.Value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 班次标签映射编辑区域 -->
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.SelectedShiftsIds && stateData.vmModel.SelectedShiftsIds.length > 0">
							<el-form-item>
								<template #label>
									<WtmLabelTooltip label="班次标签设置" tooltip="为每个选中的班次设置对应的标签" />
								</template>
								<div class="shift-tag-mapping">
									<div v-for="shift in selectedShiftsWithNames" :key="shift.value" class="shift-tag-item">
										<div class="shift-name">{{ shift.text }}</div>
										<el-select
											v-model="stateData.vmModel.ShiftTagMapping[shift.value]"
											placeholder="选择标签"
											class="tag-selector"
											clearable
											@change="onShiftTagMappingChange(shift.value, $event)"
										>
											<el-option v-for="tag in shiftTagOptions" :key="tag.value" :label="tag.label" :value="tag.value"></el-option>
										</el-select>
									</div>
								</div>
							</el-form-item>
						</el-col>

						<!-- 空状态提示 -->
						<el-col :xs="24" :lg="24" class="mb20" v-else-if="stateData.AllSysAttendanceShifts.length > 0">
							<el-alert title="请先选择班次，然后为每个班次设置对应的标签" type="info" :closable="false" show-icon></el-alert>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-time"></i>
						<span>工时折算</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_StandardWorkMinutes_FormItem"
								prop="Entity.StandardWorkMinutes"
								:rules="[{ required: true, message: '标准工作时长为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="标准工作时长" tooltip="班组标准工作时长，单位为分钟" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.StandardWorkMinutes"
									class="width100"
									:min="0"
									placeholder="请输入标准工作时长"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_AttendanceDays_FormItem"
								prop="Entity.AttendanceDays"
								:rules="[{ required: true, message: '折算出勤天数为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="折算出勤天数" tooltip="根据标准工作时长折算的考勤天数" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.AttendanceDays"
									class="width100"
									:min="0"
									:precision="2"
									placeholder="请输入折算出勤天数"
								></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysAttendanceShiftGroupApi as api } from '/@/views/hr/sysattendanceshiftgroup/api';
import other from '/@/utils/other';
import { ISysAttendanceShiftGroupVm } from '/@/views/hr/sysattendanceshiftgroup/api/interface';
import { IViewModel } from '/@/types/common';
import SchedulePreview from '/@/components/schedulePreview/index.vue';
import { calculateMonthlySchedule } from '/@/utils/scheduleCalculator';

// 默认工作日选项
// 排班类型选项
const SHIFT_TYPES = [
	{ key: '行政班', value: '行政班', label: '行政班' },
	{ key: '三班倒', value: '三班倒', label: '三班倒' },
	{ key: '两班倒', value: '两班倒', label: '两班倒' },
	{ key: '上一休二', value: '上一休二', label: '上一休二' },
];

// 班次标签选项
const shiftTagOptions = [
	{ value: 'A', label: 'A', color: '#67c23a' },
	{ value: 'B', label: 'B', color: '#409eff' },
	{ value: 'C', label: 'C', color: '#e6a23c' },
];

// 按钮文本常量
const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const stateData = reactive<IViewModel<ISysAttendanceShiftGroupVm>>({
	vmModel: {
		Entity: {
			Name: null,
			Description: null,
			Type: null,
			SchedulePattern: null,
			Shifts: null,
			Order: null,
			AttendanceDays: null,
			StandardWorkMinutes: null,
		},
		ActionName: null,
		IsMyApprove: null,
		SelectedShiftsIds: [],
		ShiftTagMapping: {},
		WorkDays: [],
		WorkDate: null,
		ShiftTag: null,
	},
	SimpleSchedule: {} as { [key: string]: string }, // 排班预览数据，键为日期，值为班次类型
	AllSysAttendanceShifts: [],
	shiftItems: [],
	allShiftItems: [],
});

const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 简化数据处理函数
const processApiResponse = (response: any, defaultValue: any = []) => {
	return response?.status === 'fulfilled' ? response.value : defaultValue;
};

// 计算属性：获取选中班次的详细信息
const selectedShiftsWithNames = computed(() => {
	if (!stateData.vmModel.SelectedShiftsIds || stateData.vmModel.SelectedShiftsIds.length === 0) {
		return [];
	}

	return stateData.vmModel.SelectedShiftsIds.map((shiftId) => {
		const shift = stateData.AllSysAttendanceShifts.find((item: any) => item.Value === shiftId);
		return {
			value: shiftId,
			text: shift ? shift.Text : shiftId,
		};
	});
});

// 班次选择变化处理
const onShiftsSelectionChange = (selectedIds: string[]) => {
	const currentMapping = (stateData.vmModel.ShiftTagMapping as Record<string, string | null>) || {};
	const newMapping: Record<string, string | null> = {};

	// 保留仍然选中的班次的标签映射
	selectedIds.forEach((shiftId) => {
		if (currentMapping[shiftId] !== undefined && currentMapping[shiftId] !== null && currentMapping[shiftId] !== '') {
			newMapping[shiftId] = currentMapping[shiftId];
		}
		// 新选中的班次不设置默认值，保持为 undefined，后续会被处理为 null
	});

	(stateData.vmModel.ShiftTagMapping as Record<string, string | null>) = newMapping;
};

// 班次标签变化处理
const onShiftTagMappingChange = (shiftId: string, tagValue: string | null | undefined) => {
	if (!stateData.vmModel.ShiftTagMapping) {
		stateData.vmModel.ShiftTagMapping = {};
	}
	// 当清空选择时，tagValue 为 null、undefined 或空字符串，统一设置为 null
	(stateData.vmModel.ShiftTagMapping as Record<string, string | null>)[shiftId] = tagValue && tagValue !== '' ? tagValue : null;
};

// 简化班次数据过滤
const filterShiftItemsByType = (type: string) => {
	const rawItems = stateData.allShiftItems?.[type] || [];
	stateData.shiftItems = rawItems.map((item: any) => (typeof item === 'string' ? { Text: item, Value: item } : item));

	// 自动设置默认班次标签
	if (stateData.shiftItems.length > 0 && !stateData.vmModel.ShiftTag) {
		stateData.vmModel.ShiftTag = stateData.shiftItems[0].Value;
	}
};

// 计算排班预览
const calculateSchedule = () => {
	const { Type } = stateData.vmModel.Entity;
	const { WorkDate, ShiftTag } = stateData.vmModel;

	if (!Type || !WorkDate) {
		stateData.SimpleSchedule = {};
		return;
	}

	// 从 allShiftItems 获取班次序列
	const shiftSequence = stateData.allShiftItems?.[Type] || [];

	// 使用工具函数计算排班，传递班次标签和班次序列
	stateData.SimpleSchedule = calculateMonthlySchedule({
		shiftType: Type as '三班倒' | '两班倒' | '上一休二',
		workDate: WorkDate,
		shiftTag: ShiftTag || undefined, // 传递班次标签，null 转为 undefined
		shiftSequence: shiftSequence.length > 0 ? shiftSequence : undefined, // 传递班次序列
	});
};

// 排班类型变化处理
const onTypeChange = async (type: string) => {
	// 清空所有相关字段
	Object.assign(stateData.vmModel, {
		WorkDays: [],
		WorkDate: null,
		ShiftTag: null,
		Entity: { ...stateData.vmModel.Entity, SchedulePattern: null },
	});

	// 清空排班预览数据
	stateData.SimpleSchedule = {};

	if (!type) return;

	// 根据类型初始化字段
	if (type === '行政班') {
		stateData.vmModel.WorkDays = [];
	} else {
		stateData.vmModel.WorkDate = new Date().toISOString().split('T')[0];
		// 自动计算排班预览
		setTimeout(() => calculateSchedule(), 100);
	}

	filterShiftItemsByType(type);
};

// 工作日期变化处理
const onWorkDateChange = () => {
	if (stateData.vmModel.Entity.Type && stateData.vmModel.Entity.Type !== '行政班') {
		calculateSchedule();
	}
};

// 班次标签变化处理
const onShiftTagChange = () => {
	if (stateData.vmModel.Entity.Type && stateData.vmModel.Entity.Type !== '行政班') {
		calculateSchedule();
	}
};

// 排班预览变化处理
const onScheduleChange = (scheduleData: Record<string, string>) => {
	stateData.SimpleSchedule = scheduleData;
};

// 简化保存逻辑
const prepareSubmitData = () => {
	const submitData = JSON.parse(JSON.stringify(stateData.vmModel));

	if (!submitData.Entity.ID) {
		delete submitData.Entity.ID;
	}

	const isAdminShift = submitData.Entity.Type === '行政班';

	if (isAdminShift) {
		Object.assign(submitData, {
			WorkDays: Array.isArray(submitData.WorkDays) ? submitData.WorkDays : [],
			WorkDate: null,
			ShiftTag: null,
			Entity: { ...submitData.Entity, SchedulePattern: null },
		});
	} else {
		Object.assign(submitData, {
			WorkDays: [],
			WorkDate: submitData.WorkDate || new Date().toISOString().split('T')[0],
			ShiftTag: submitData.ShiftTag || stateData.shiftItems[0]?.Value || '',
			Entity: { ...submitData.Entity, SchedulePattern: null },
		});
	}

	// 处理 ShiftTagMapping：将空字符串转换为 null，如果所有值都是 null 或空字符串，或者对象为空，则整个对象传 null
	if (submitData.ShiftTagMapping && Object.keys(submitData.ShiftTagMapping).length > 0) {
		const mapping = submitData.ShiftTagMapping as Record<string, string | null>;
		const cleanedMapping: Record<string, string | null> = {};
		let hasValidValue = false;

		// 清理映射，将空字符串转换为 null
		Object.keys(mapping).forEach((key) => {
			const value = mapping[key];
			if (value && value !== '') {
				cleanedMapping[key] = value;
				hasValidValue = true;
			} else {
				cleanedMapping[key] = null;
			}
		});

		// 如果所有值都是 null，则整个 ShiftTagMapping 传 null
		if (!hasValidValue) {
			submitData.ShiftTagMapping = null;
		} else {
			submitData.ShiftTagMapping = cleanedMapping;
		}
	} else {
		submitData.ShiftTagMapping = null;
	}

	return submitData;
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(prepareSubmitData()),
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	try {
		const [shiftResponse, shiftsListResponse, entityResponse] = await Promise.allSettled([
			api().getShiftItems(),
			other.getSelectList('/api/SysAttendanceShiftGroup/GetSysAttendanceShifts', [], false),
			api().get(stateData.vmModel.Entity.ID ?? ''),
		]);

		// 处理所有数据
		stateData.allShiftItems = processApiResponse(shiftResponse, []);
		stateData.AllSysAttendanceShifts = processApiResponse(shiftsListResponse, []);

		// 加载实体数据
		const entityData = processApiResponse(entityResponse, null);
		if (entityData) {
			// 直接使用接口返回的数据
			other.setValue(stateData.vmModel, entityData);

			// 回显ShiftTagMapping数据
			if (entityData.ShiftTagMapping) {
				stateData.vmModel.ShiftTagMapping = entityData.ShiftTagMapping;
			}
		}

		// 如果有排班类型，过滤对应的班次
		if (stateData.vmModel.Entity.Type) {
			filterShiftItemsByType(stateData.vmModel.Entity.Type);
		}

		// 班次预览 - 直接使用接口返回的SimpleSchedule数据
		if (entityData?.SimpleSchedule) {
			stateData.SimpleSchedule = entityData.SimpleSchedule;
		}
	} catch (error) {
		stateData.AllSysAttendanceShifts = [];
	}
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>

<style scoped>
.space-y-3 > * + * {
	margin-top: 12px;
}

.mb-3 {
	margin-bottom: 12px;
}

.mb20 {
	margin-bottom: 20px;
}

.form-section {
	margin-bottom: 32px;
	padding-bottom: 24px;
	border-bottom: 1px solid #ebeef5;
}

.form-section:last-child {
	border-bottom: none;
	margin-bottom: 0;
	padding-bottom: 0;
}

.section-title {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 20px;
	font-weight: 600;
	font-size: 16px;
	color: #303133;
}

.section-title i {
	color: #409eff;
	font-size: 18px;
}

.width100 {
	width: 100%;
}

/* 紧凑简约的班次标签映射样式 - 占满屏幕宽度 */
.shift-tag-mapping {
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	background-color: #fafafa;
	padding: 16px;
	display: flex;
	flex-direction: column;
	gap: 12px;
	width: 100%;
}

.shift-tag-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 16px;
	background-color: #ffffff;
	border: 1px solid #e4e7ed;
	border-radius: 4px;
	width: 100%;
}

.shift-name {
	color: #606266;
	flex: 1;
	margin-right: 16px;
	font-size: 14px;
}

.tag-selector {
	width: 120px;
	flex-shrink: 0;
}
</style>
